<?php

namespace MoChat\App\Statistic\Action\WorkOutside;

use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Arr;
use MoChat\App\Client\Constants\ClientFollowRecordTypeCode;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 跟进统计列表
 * @Controller
 */
class Call extends AbstractAction
{
    private function typeEnum($data): array
    {
        $timeRange = [
            'start_time' => date('Y-m-d 00:00:00'),
            'end_time' => date('Y-m-d H:i:s'),
        ];
        //今日
        if ($data['type'] == 1) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //昨日
        if ($data['type'] == 2) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-1 day')),
                'end_time' => date('Y-m-d 00:00:00'),
            ];
        }
        //本月
        if ($data['type'] == 3) {
            $timeRange = [
                'start_time' => date('Y-m-01 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //上月
        if ($data['type'] == 4) {
            $start = date('Y-m-01 00:00:00', strtotime('-1 month'));
            $timeRange = [
                'start_time' => date('Y-m-01 00:00:00', strtotime('-1 month')),
                'end_time' => date('Y-m-d H:i:s', strtotime('+1 month', strtotime($start))),
            ];
        }
        //本周
        if ($data['type'] == 5) {
            $week = date('w');
            $day = $week ? $week - 1 : 6;
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-' . $day . ' day')),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //默认
        return array_merge($data, $timeRange);
    }

    /**
     * 外勤列表
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workOutside/call", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $data = $this->typeEnum($data);
        $data['workEmployeeId'] = $user['isRoot'] == 1 ? 0 : $user['workEmployeeId'];
        //打卡数据
        $clockCount = Db::table('clock_record')
//            ->when($data['workEmployeeId'] > 0, function (Builder $query) use ($data) {
//                $query->where('work_employee_id', $data['workEmployeeId']);
//            })
            ->where('created_at', '>=', $data['start_time'])
            ->where('created_at', '<', $data['end_time'])
            ->whereNull('deleted_at')
            ->count();
        //进店（去重）次数
        $enterShopCount = Db::table('clock_record')
//            ->when($data['workEmployeeId'] > 0, function (Builder $query) use ($data) {
//                $query->where('work_employee_id', $data['workEmployeeId']);
//            })
            ->where('created_at', '>=', $data['start_time'])
            ->where('created_at', '<', $data['end_time'])
            ->whereNull('deleted_at')
            ->selectRaw('COUNT(DISTINCT client_id) as count')
            ->first()
            ->count;
        //下单客户数
        $uniqueIds = Db::table('client')
//            ->when($data['workEmployeeId'] > 0, function (Builder $query) use ($data) {
//                $query->where('work_employee_id', $data['workEmployeeId']);
//            })
            ->pluck('unique_id');
        $uniqueIds || $uniqueIds = collect([]);
        $uniqueIds = $uniqueIds->toArray();
        $uniqueIds = array_filter($uniqueIds);
        $userIds = Db::connection('b2b')
            ->table('user')
            ->whereIn('unique_id', $uniqueIds)
            ->pluck('id');
        $userIds || $userIds = collect([]);
        $userIds = $userIds->toArray();
        $orderCount = Db::connection('b2b')
            ->table('user_order')
            ->whereIn('USER_ID', $userIds)
            ->where('CREATE_TIME', '>=', $data['start_time'])
            ->where('CREATE_TIME', '<', $data['end_time'])
            ->selectRaw('COUNT(DISTINCT USER_ID) as count')
            ->first()
            ->count;
        //总客户数
        $totalUserCount = count($userIds);
        //未下单客户数
        $notOrderCount = bcsub((string)$totalUserCount, $orderCount, 0);
        $orderRate = $totalUserCount > 0 ? bcdiv((string)$orderCount, (string)$totalUserCount, 6) : '0.00';
        $orderRate = bcmul($orderRate, '100', 2) . '%';
        return [
            'clock_count' => $clockCount,//签到次数
            'enter_shop_count' => $enterShopCount,//进店（去重）次数
            'order_user_count' => $orderCount,//下单客户数
            'not_order_user_count' => $notOrderCount,//未下单客户数
            'order_rate' => $orderRate,//下单率
        ];
    }
}
